#define _MULTI_THREADED
#include "allocateur_sem.h"
#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
#include <unistd.h>

#define MAX 10

//Thread array creation
sem_t sem;
pthread_mutex_t mutex_alloc = PTHREAD_MUTEX_INITIALIZER;

/*
int main() {
        //Semaphore initialization
        int i;
	sem_init(&sem, 0, MAX);

        //Thread creation and initialization
        pthread_t t1, t2, t3;
        int n = 8;
        pthread_create(&t1, NULL, thread1, (void*)n);
        pthread_create(&t2, NULL, thread2, (void*)n);
        pthread_create(&t3, NULL, thread3, (void*)n);
        //Thread execution;
        void *status;
        pthread_join(t1, &status);
        pthread_join(t2, &status);
        
        //Semaphore destruction
        sem_destroy(&sem);
        
        return 0;
}
*/
void allouer(int n, int idth) {
	pthread_mutex_lock(&mutex_alloc);
                int i;
                for(i = 0; i < n; i++) {
                        sem_wait(&sem);
                        printf("Thread %d is allocating resources (already allocated: %d)...\n", idth, i+1);
                }
        pthread_mutex_unlock(&mutex_alloc);
}

void liberer(int n, int idth) {
        int i;
        for(i = 0; i < n; i++) {
                sem_post(&sem);
                printf("Thread %d is liberating resources (already liberated: %d)...\n", idth, i+1);
        }
        printf("Thread %d liberated %d resources...\n", idth, n);       
}

/*
void *thread1(void* n) {
        int n_int = (int) n;
        allouer(n_int, 1);
        liberer(n_int, 1);
        return NULL;
}

void *thread2(void* n) {
        int n_int = (int) n; 
        allouer(n_int, 2);
        liberer(n_int, 2);
        return NULL;
}

void *thread3(void* n){
        int n_int = (int) n;
        allouer(n_int, 3);
        liberer(n_int, 3);
        return NULL;                    
}*/

